package org.gitee.weapp.controller;

import org.apache.http.HttpStatus;
import org.gitee.weapp.domain.AjaxResult;
import org.gitee.weapp.domain.entity.SysUser;
import org.gitee.weapp.service.SysUserService;
import org.gitee.weapp.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/user")
public class SysUserController {

    @Autowired
    private TokenService tokenService;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private SysUserService sysUserService;

    @PostMapping("/uploadAvatar")
    public AjaxResult uploadAvatar(@RequestParam("file") MultipartFile multipartFile) {
        SysUser sysUser = tokenService.getSysUserFromToken(request);
        if (null == sysUser) {
            return AjaxResult.error(HttpStatus.SC_NOT_FOUND, "用户未登录");
        }
        try {
            sysUserService.uploadAvatar(sysUser, multipartFile);
            return AjaxResult.success("头像上传成功");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }
    }

    @GetMapping("/getAvatar")
    public void getAvatar(@RequestParam("userId") String userId, HttpServletResponse response) {
        sysUserService.getAvatar(userId, response);
    }
}
